// import JsEncrypt from 'jsencrypt';
import CryptoJS from 'crypto-js';
import L from 'lodash';

/**
 * @des: 随机数
*/
export const AESKey = () => {
  const len = 16;
  const $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  const maxPos = $chars.length;
  let pwd = '';
  for (let i = 0; i < len; i += 1) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }

  return pwd;
};

/**
 * @des: AES
*/
const iv = CryptoJS.enc.Utf8.parse('');

/*
 * @Description: RSA 公钥加密
*/
// export const RSAEncrypt = (pwd) => {
//   const pubKey = ``;

//   const Jse = new JsEncrypt();
//   Jse.setPublicKey(pubKey);
//   return Jse.encrypt(pwd);
// };

/*
 * @Description: RSA 私钥解密
*/
// export const RsaDecrypt = (pwd) => {
//   const priKey = '私钥';

//   const Jse = new JsEncrypt();
//   Jse.setPrivateKey(priKey);
//   return Jse.decrypt(pwd);
// };

/**
 * des: AES 加密
 * @param parameter
 * @returns {*}
*/
export const AESEncrypt = (word, Key) => {
  const key = CryptoJS.enc.Utf8.parse(Key || '8vPT7i3jOuPoNac7');
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
  const encryptedHexStr = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
  return encryptedHexStr.toString();
  // return encrypted.toString();
};

/**
 * des: AES 解密
 * @param parameter
 * @returns {*}
*/
export const AESDecrypt = (word, Key) => {
  const key = CryptoJS.enc.Utf8.parse(Key);
  const decrypt = CryptoJS.AES.decrypt(word, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
};

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
/* eslint-disable */
export function filterObj(obj) {
  if (!(typeof obj == 'object')) {
    return;
  }
  for (const key in obj) {
    if (obj.hasOwnProperty(key)
      && (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
      delete obj[key];
    }
  }
  return obj;
}

/**
 * 获得一个随机数
 */
export const getRandom = () => (Math.random() + '').slice(2)

/**
 * 从blob创建URL以预览或下载
 */
export const createFileUrl = (b) => {
  const url = window.URL.createObjectURL(b);
  return {
    url,
    off: () => window.URL.revokeObjectURL(url),
    name
  };
}

/**
 * 格式化headers，全部小写
 */
export const headersFormat = (h) => L.mapKeys(h, (i, v) => (v + '').toLowerCase());

/**
 * 获取二进制流附件请求content-disposition中的文件名
 */
export const getContentDispositionFilename = (s = '') => window.decodeURIComponent(s.match(/filename=(.*\.(xlsx|xls|doc|docx|pdf|txt))/)[1] || '');
